#include "graphics/render.h"
#include "graphics/render_private.h"

#include "system/window.h"

#include <stdio.h>
#include <stdbool.h>

unsigned esdlGetFrameRate() {
    return esdlGetRender()->frameRate;
}

void esdlSetFrameRate(unsigned frameRate) {
    esdlGetRender()->frameRate = frameRate;
}

void _esdlBlit(EsdlSprite* sprite) {
    SDL_Rect srcRect;
    srcRect.x = sprite->visiblePart.x;
    srcRect.y = sprite->visiblePart.y;
    srcRect.w = esdlGetVisibleWidth(sprite);
    srcRect.h = esdlGetVisibleHeight(sprite);

    SDL_Rect destRect;
    destRect.x = esdlgetAbsoluteXPosition(sprite);
    destRect.y = esdlGetAbsoluteYPosition(sprite);
    destRect.w = sprite->visiblePart.w;
    destRect.h = sprite->visiblePart.h;
    
    SDL_BlitSurface(esdlGetSurface(sprite), &srcRect, window.screen, &destRect);
}

void _esdlRenderInit(EsdlRender* render) {
    render->frameRate = 50;
    render->elapsedTime = 0;
    render->updateTime = 0;
}

void _esdlRenderSprites(EsdlSprite* sprite) {
    //Affiche le sprite
    if (sprite->show) {
        _esdlBlit(sprite);

        // Affiche ses enfants
        EsdlLinkedList q = sprite->children;
        while (q != NULL) {
            _esdlRenderSprites((EsdlSprite*) q->data);
            q = q->next;
        }    
    }
}

void _esdlRenderScreen(EsdlRenderCallback callback) {
    // Clear Screen	
    SDL_FillRect(window.screen, NULL, SDL_MapRGB(window.screen->format, 0, 0, 0));

    // Call the user event callback
    if (callback != NULL) {
        callback(esdlGetRender()->elapsedTime);
    }

    // Display sprites
    _esdlRenderSprites(esdlGetScreen());

    // Display screen
    SDL_Flip(window.screen);

    // Frame time processing
    if (esdlGetRender()->frameRate > 0 && SDL_GetTicks() - esdlGetRender()->updateTime < 1000 / esdlGetRender()->frameRate) {
        SDL_Delay(1000 / esdlGetRender()->frameRate - (SDL_GetTicks() - esdlGetRender()->updateTime));
    }

    esdlGetRender()->elapsedTime = SDL_GetTicks() - esdlGetRender()->updateTime;
    esdlGetRender()->updateTime = SDL_GetTicks();
}